﻿using System;
using System.Windows;

namespace DotNetImage.Imaging.Filters
{
    public class Pixelate : FilterBase
    {
        private Point[,] points = null;

        [ParameterAttribute(Name = "Pixel", DefaultValue = 0, MaxValue=Int32.MaxValue, MinValue=0, Step=1)]
        public short Pixel { get; set; }
        public bool Grid { get; set; }


        protected override void PrepareData(DotNetImage bmp)
        {
            bmp.CreatePixelCopy();
            points = new Point[nWidth, nHeight];
        }

        protected override void ProcessPixel(ref Pixel pix, uint x, uint y)
        {
            int newX = (int)(Pixel - x % Pixel);

            if (Grid && newX == Pixel)
                points[x, y].X = -x;
            else if (x + newX > 0 && x + newX < nWidth)
                points[x, y].X = newX;
            else
                points[x, y].X = 0;

            int newY = (int)(Pixel - y % Pixel);

            if (Grid && newY == Pixel)
                points[x, y].Y = -y;
            else if (y + newY > 0 && y + newY < nHeight)
                points[x, y].Y = newY;
            else
                points[x, y].Y = 0;
        }

        protected override void PostProcessing(DotNetImage bmp)
        {
            base.PostProcessing(bmp);
            OffsetFilter filter = new OffsetFilter();
            filter.Offset = points;
            filter.Apply(bmp);
        }
    }
}
